package com.qr.read;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import java.io.FileInputStream;

/**
 * 计算个公式
 */
public class ReadSum {

    public static void main(String[] args) throws Exception{

        String path = "E:\\workspace\\GitRepository\\java-framework\\poi\\poi-use\\src\\main\\resources\\";

        //获取文件流
        FileInputStream fileInputStream = new FileInputStream(path+"ai.xlsx");

        XSSFWorkbook sheets = new XSSFWorkbook(fileInputStream);

        //得到第一个表
        XSSFSheet sheetAt = sheets.getSheetAt(0);

        XSSFRow row = sheetAt.getRow(10);

        XSSFCell cell = row.getCell(0);

        //获取计算公式
        FormulaEvaluator formulaEvaluator = new XSSFFormulaEvaluator(sheets);

        CellType cellType = cell.getCellType();

        switch (cellType){
            case FORMULA:
                //拿到计算公式
                String cellFormula = cell.getCellFormula();
                System.out.println(cellFormula);

                //计算
                CellValue evaluate = formulaEvaluator.evaluate(cell);
                //将值格式为一个字符串
                String s = evaluate.formatAsString();

                System.out.println(s);
                break;
        }

    }
}
